from flask import render_template, redirect, url_for, abort, flash, request, jsonify
from flask_login import login_required, current_user
from . import main
from .forms import EditProfileForm, EditProfileAdminForm
from .. import db
from ..models import Role, User
from ..decorators import admin_required
import csv, os
from ..alg import fix, get_valid_data
import numpy, math


@main.route('/')
def index():
    return render_template('index.html')


@main.route('/user/<username>')
def user(username):
    user = User.query.filter_by(username=username).first_or_404()
    return render_template('user.html', user=user)


@main.route('/edit-profile', methods=['GET', 'POST'])
@login_required
def edit_profile():
    form = EditProfileForm()
    if form.validate_on_submit():
        current_user.name = form.name.data
        current_user.location = form.location.data
        current_user.about_me = form.about_me.data
        db.session.add(current_user)
        flash('Your profile has been updated.')
        return redirect(url_for('.user', username=current_user.username))
    form.name.data = current_user.name
    form.location.data = current_user.location
    form.about_me.data = current_user.about_me
    return render_template('edit_profile.html', form=form)


@main.route('/edit-profile/<int:id>', methods=['GET', 'POST'])
@login_required
@admin_required
def edit_profile_admin(id):
    user = User.query.get_or_404(id)
    form = EditProfileAdminForm(user=user)
    if form.validate_on_submit():
        user.email = form.email.data
        user.username = form.username.data
        user.confirmed = form.confirmed.data
        user.role = Role.query.get(form.role.data)
        user.name = form.name.data
        user.location = form.location.data
        user.about_me = form.about_me.data
        db.session.add(user)
        flash('The profile has been updated.')
        return redirect(url_for('.user', username=user.username))
    form.email.data = user.email
    form.username.data = user.username
    form.confirmed.data = user.confirmed
    form.role.data = user.role_id
    form.name.data = user.name
    form.location.data = user.location
    form.about_me.data = user.about_me
    return render_template('edit_profile.html', form=form, user=user)


@main.route('/upload-file', methods=['GET', 'POST'])
def upload_file():
    try:
        upload_files = request.files.getlist('file')
        upload_files[0].filename = 'raw_data.csv'
        file_path = os.path.join(os.getcwd(), upload_files[0].filename)
        upload_files[0].save(file_path)
        pass
    except Exception as e:
        pass
    return redirect(url_for('main.index'))


@main.route('/upload-fix-file', methods=['GET', 'POST'])
def upload_fix_file():
    try:
        upload_files = request.files.getlist('file')
        upload_files[0].filename = 'fix_data.csv'
        file_path = os.path.join(os.getcwd(), upload_files[0].filename)
        upload_files[0].save(file_path)
        pass
    except Exception as e:
        pass
    return redirect(url_for('main.index'))


@main.route('/calculate', methods=['GET'])
def calculate():
    try:
        data = []
        file_path = os.path.join(os.getcwd(), 'raw_data.csv')
        with open(file_path, 'r') as myFile:
            lines = csv.reader(myFile)
            for line in lines:
                data.append(line)
        data = get_valid_data(data)
        result = []
        if len(data) >= 1 and len(data[0]) >= 1:
            result = fix(data)
    except Exception as e:
        pass
    return jsonify(result)


@main.route('/show', methods=['GET'])
def show():
    try:
        result = []
        file_path = os.path.join(os.getcwd(), 'fix_data.csv')
        with open(file_path, 'r') as myFile:
            lines = csv.reader(myFile)
            for line in lines:
                result.append(line)
    except Exception as e:
        pass
    return jsonify(result)
